<?php
require_once("phpmailer/class.phpmailer.php"); 
if(!defined('IN_WEBSHOP')) {
    exit('Access Denied');
}

///*************   use in linux    **************////
//function sendhtmlmail($from_name,$from_email,$to_name,$to_email,$subject,$content){
//	$from_email="info@acuityworld.com";
//	$from = "From: $from_name <$from_email>";
//	$to   = "=?" . "iso-8859-1" . "?B?" .base64_encode(addslashes($to_name)). "?=<$to_email>";
//  
//	$boundary = uniqid( "");
//	$headers =  "From: $from_name <$from_email>\r\n";
//	$headers .= "Content-type: text/html;charset=iso-8859-1;boundary=\"$boundary\"";
//	
//	mail($to,$subject,$content,$headers);
//}
//function sendHideMail($from_name,$from_email,$to_name,$to_email,$subject,$content)
//{
//	$from = "From: $from_name <$from_email>";
//	$to   = $to   = "=?" . "iso-8859-1" . "?B?" .base64_encode(addslashes($to_name)). "?=<$to_email>";
//  
//	$boundary = uniqid( "");
//	$headers =  "From: $from_name <$from_email>\r\n";
//	$headers .= "Content-type: text/html;charset=iso-8859-1;boundary=\"$boundary\"";
//	mail($to,$subject,$content,$headers);
//}
///*************   use in linux    **************////


function sendhtmlmail($from_name,$from_email,$to_name,$to_email,$subject,$content)
{
	$mail = new PHPMailer();
	$mail->IsSMTP();
	$mail->SMTPAuth   = true;                  // enable SMTP authentication
	$mail->Port       = 25;                   // set the SMTP port 
	
	$mail->Host = "mail.authsmtp.com"; // SMTP servers 
	$mail->Username = "ac31991"; // SMTP username `NGq???ݭn[ @W	
	$mail->Password = "KFr0Gs071175"; // SMTP password 	
	$mail->From = $from_email; //$from_email; // ?H?c	
	
	$mail->CharSet = "iso-8859-1"; // 
	$mail->Encoding = "base64"; 
	$mail->FromName   = $from_name;
	$mail->Subject    = $subject;
	$mail->Body       = $content;                //HTML Body
		
	$mail->WordWrap   = 50; // set word wrap	
	$mail->AddAddress($to_email,$to_name);
	$mail->IsHTML(true); 						// send as HTML
	$mail->SetLanguage("dk");
	if(!$mail->Send()) {
	  echo "Send mail error<p>"; 
	  echo "Message: " . $mail->ErrorInfo; 
	  exit; 
	} 
}
function sendHideMail($from_name,$from_email,$to_name,$to_email,$subject,$content){
 
	$mail = new PHPMailer(); 
	$mail->IsSMTP(); // send via SMTP
	
	$mail->Host = "mail.authsmtp.com"; // SMTP servers 
	$mail->Username = "ac31991"; // SMTP username `NGq???ݭn[ @W	
	$mail->Password = "KFr0Gs071175"; // SMTP password 	
	$mail->From = "info@acuityworld.com"; //$from_email; // ?H?c	

	$mail->FromName   = $from_name; // ?H			
	$mail->SMTPAuth = true; // turn on SMTP authentication 	
	$mail->Port = 25; //default is 25, gmail is 465 or 587
	$mail->CharSet = "iso-8859-1"; // ?wrŶI	
	$mail->Encoding = "base64"; 
	$mail->AddAddress($to_email,$to_name); // H?cMmW	
	$mail->IsHTML(true); // send as HTML 
	$mail->Subject = $subject;
	$mail->Body	= $content;
	$mail->SetLanguage("dk");
	if(!$mail->Send()) 
	{ 
	  echo "Send mail error<p>"; 
	  echo "Message: " . $mail->ErrorInfo; 
	  exit; 
	}
}

function db2Init() {
    global $db2, $dbhost2, $dbuser2, $dbpw2, $dbname2, $pconnect2;

    $db2 = new DB($dbhost2, $dbuser2, $dbpw2, $dbname2, $pconnect2);
    unset($dbhost2, $dbuser2, $dbpw2, $dbname2, $pconnect2);
}

function getMyParam($param, $method='pg') {
    global $$param;
    if ( $method == 'pg' && ( isset($_POST[$param]) || isset($_GET[$param]) ) ) {
        $$param = ( isset($_POST[$param]) ) ? $_POST[$param] : $_GET[$param];
    }
    if ( $method == 'p' && isset($_POST[$param]) ) {
        $$param = $_POST[$param];
    }
    if ( $method == 'g' && isset($_GET[$param]) ) {
        $$param = $_GET[$param];
    }
    if ( $method == 'c' && isset($_COOKIE[$param]) ) {
        $$param = $_COOKIE[$param];
    }
    if ( $method == 's' && isset($_SESSION[$param]) ) {
        $$param = $_SESSION[$param];
    }
    if ( $method == 'r' && isset($_REQUEST[$param]) ) {
        $$param = $_REQUEST[$param];
    }
    if ( $method == 'f' && isset($_FILES[$param]) ) {
        $$param = $_FILES[$param];
    }
}
function isLogin() 
{
	if(isUserLogin() || isPromoterLogin())
		return true;
	else
		return false;
}
function isUserLogin() {
    global $timestamp, $cookietime, $webshop_uid;
    @list($webshop_uid,$webshop_useremail, $login_time)=explode("\t",  base64_decode(GetCookie('webshopuser')));

    if (!$webshop_uid || !is_numeric($webshop_uid) || $webshop_uid <= 0 || $timestamp-$login_time > 1800) {
        Cookie('webshopuser','',0);
        return false;
    } else {
        Cookie("webshopuser",base64_encode($webshop_uid."\t".$webshop_useremail."\t".$timestamp), $cookietime);
        return true;
    }

}

function isPromoterLogin() {
    global $timestamp, $cookietime, $promoter_uid,$promoter_faq1,$login_time;
    @list($promoter_uid,$email,$promoter_faq1,$login_time)=explode("\t",  base64_decode(GetCookie('webshoppromoter')));	
    if (!$promoter_uid || !is_numeric($promoter_uid) || $promoter_uid <= 0 || $timestamp-$login_time > 1800) {
        Cookie('webshoppromoter','',0);
        return false;
    } else {
		Cookie("webshoppromoter",base64_encode($promoter_uid."\t".$email."\t".$promoter_faq1."\t".$timestamp), $cookietime);
		return true;
    }

}



// ??promoterno??
function isPromoterId($pid) {
    global $db;
    
    $sql = "SELECT * FROM `promoter_info` WHERE `id` = '$pid' AND `status` = '1' AND `rank` > 0 ";
    $rs = $db->get_one($sql);

    if (!empty($rs)) {
        return true;
    } else {
        return false;
    }
}

function daddslashes($string, $force = 0) {
    if(!$GLOBALS['magic_quotes_gpc'] || $force) {
        if(is_array($string)) {
            foreach($string as $key => $val) {
                $string[$key] = daddslashes($val, $force);
            }
        } else {
            $string = addslashes($string);
        }
    }
    return $string;
}


function debuginfo() {
    if($GLOBALS['debug']) {
        global $db, $starttime, $debuginfo, $debug_out;
        $mtime = explode(' ', microtime());
        $debuginfo = array('time' => number_format(($mtime[1] + $mtime[0] - $starttime), 6), 'queries' => $db->querynum);
        $debug_out = "Processed in " . $debuginfo['time'] . " second(s), " . $debuginfo['queries'] . " queries";
        return TRUE;
    } else {
        return FALSE;
    }
}

function Cookie($ck_Var,$ck_Value,$ck_Time='F'){
    global $cookietime,$cookiedomain,$cookiepath;
    if($ck_Time=='F') $ck_Time = $cookietime;
    $S=$_SERVER['SERVER_PORT']=='443' ? 1:0;
	setcookie($ck_Var,$ck_Value,$ck_Time,$cookiepath,$cookiedomain,$S);
}

function GetCookie($Var){
    if (isset($_COOKIE[$Var])) {
        return $_COOKIE[$Var];
    } else {
        return false;
    }
}

function getUnixTime($in_time) {
    //2000-01-01 10:00
    if (preg_match("/^([\d]{4})-([\d]{2})-([\d]{2})\s([\d]{2}):([\d]{2})$/i", $in_time, $match_array)) {
        return mktime($match_array[4], $match_array[5], 0, $match_array[2], $match_array[3], $match_array[1]);
    } else {
        return false;
    }
}

function PrintEot($template,$EXT="htm"){
    global $tplpath;
    if(!$template) $template='N';
    $path=WEBSHOP_ROOT."templates/$tplpath/$template.$EXT";
    !file_exists($path) && $path=WEBSHOP_ROOT."templates/default/$template.$EXT";
    return $path;
}

function PrintPrint($template,$EXT="htm"){
    global $tplpath;
    if(!$template) $template='N';
    $path=WEBSHOP_ROOT."templates/print/$template.$EXT";
    return $path;
}

function readover($filename,$method="rb"){
    strpos($filename,'..')!==false && exit('Forbidden');
    if($handle=@fopen($filename,$method)){
        flock($handle,LOCK_SH);
        $filedata=@fread($handle,filesize($filename));
        fclose($handle);
    }
    return $filedata;
}

function writeover($filename,$data,$method="rb+",$iflock=1,$check=1,$chmod=1){
    $check && strpos($filename,'..')!==false && exit('Forbidden');
    touch($filename);
    $handle=fopen($filename,$method);
    if($iflock){
        flock($handle,LOCK_EX);
    }
    fwrite($handle,$data);
    if($method=="rb+") ftruncate($handle,strlen($data));
    fclose($handle);
    $chmod && @chmod($filename,0777);
}

function delPicture($file_name, $dir="attachments") {
    $file_path = WEBSHOP_ROOT . $dir . '/' . $file_name;
    if (file_exists($file_path)) {
        @unlink($file_path);
    }
}

function ispage($number) {
    return !empty($number) && preg_match ("/^([0-9]+)$/", $number);
}


function sendmail($from_name,$from_email,$to_name,$to_email,$subject,$content){

    $from = "From: $from_name <$from_email>";
    $to   = "$to_name <$to_email>";
    //echo $content;exit;
    //?'
    @mail($to,$subject,$content,$from) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");

}
function mb_mime_header($string, $encoding=null, $linefeed="\r\n") {
  if(!$encoding) $encoding = mb_internal_encoding();
  $encoded = '';

   $encoded .= "=?$encoding?B?"
             . base64_encode($string)
             . "?=$linefeed";
  return $encoded;
}


function getExt($filename) {
    if (strstr($filename, ".")) {
        $tmp_ary = explode(".", $filename);
        return array_pop($tmp_ary);
    }

    return false;
}

// ??
function PrintMenu() {
    global $menu_id, $MENU_ARY;
    $menu_id = key_exists($menu_id, $MENU_ARY) ? $menu_id : 0;


    $out = '<table width="100%"  border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td height="14" bgcolor="#1e3674"><img src="images/transparent.gif" width="1" height="14"></td>
                  </tr>
                  <tr>
                    <td height="26" valign="top" background="images/menu/back.gif"><table height="25"  border="0" cellpadding="0" cellspacing="0" class="menu">
                      <tr align="center">';
    foreach ($MENU_ARY as $k=>$v) {
        if ($k == $menu_id) {
            $out .= '<td width="' . $v['width'] . '" bgcolor="#b6c3d6" class="menu">' . $v['name'] . '</td>';
        } else {
            $out .= '<td width="' . $v['width'] . '" onmouseover="style.backgroundColor=\'#b6c3d6\'" onmouseout="style.backgroundColor=\'#FFFFFF\'"><a href="' . $v['href'] . '">' . $v['name'] . '</a></td>';
        }
    }

    $out .= '     </tr>
                    </table></td>
                  </tr>
                </table>';

    return $out;

}

// promoter ?
function PrintPromoterMenu() {
    global $promoter_menu_id, $PROMOTER_MENU_ARY;
    $promoter_menu_id = key_exists($promoter_menu_id, $PROMOTER_MENU_ARY) ? $promoter_menu_id : 0;

    $out = '';
    $index = 1;
    foreach ($PROMOTER_MENU_ARY as $k=>$v) {        
        if ($index>1) {
            $out .= ' | ';
        }
        if ($k == $promoter_menu_id) {
            $out .= $v['name'];
        } else {
            $out .= '<a href="' . $v['href'] . '">' . $v['name'] . '</a>';
        }
        $index++;
    }

    return $out;
    
}


// ?med_other?
function getMvalue($mk,$mvalue="mvalue") {
    global $db;

    $sql = "SELECT `$mvalue` FROM `med_other` WHERE `mkey` = '$mk' ORDER BY `mkey`";
    $t_value = $db->get_one($sql);

    if (empty($t_value)) {
        return false;
    }

    return $t_value[$mvalue];

}

// med_other?
function setMvalue($mk, $mv) {
    global $db;

    $sql = "update `med_other` set `mvalue` = '$mv' WHERE `mkey` = '$mk' limit 1";
    if (!$db->query($sql)) {
        return false;
    }

}




// ?cus_order_tmp?
function getCartInfo($uid) {
    global $db;

    $sql = "SELECT `info` FROM `cus_order_tmp` WHERE `user_id` = '$uid'";
    $t_value = $db->get_one($sql);

    if (empty($t_value)) {
        return false;
    }

    return $t_value['info'];

}

// cus_order_tmp?
function setCartInfo($uid, $mv) {
    global $db;

    if(strstr($mv, "'"))  {
        $mv = str_replace("'", "\'", $mv);        
    }
    $sql = "SELECT `info` FROM `cus_order_tmp` WHERE `user_id` = '$uid'";
    $t_value = $db->get_one($sql);
    if (!empty($t_value)) {
        $sql = "update `cus_order_tmp` set `info` = '$mv' WHERE `user_id` = '$uid' limit 1";
    } else {
        $sql = "insert into `cus_order_tmp` (`user_id`, `info`) values ('$uid', '$mv')";
    }
    if (!$db->query($sql)) {
        return false;
    }
}
// ?cus_order_tmp?
function getPromoterCartInfo($pid) {
    global $db;

    $sql = "SELECT `info` FROM `promoter_order_tmp` WHERE `promoter_id` = '$pid'";
    $t_value = $db->get_one($sql);

    if (empty($t_value)) {
        return false;
    }

    return $t_value['info'];

}

// cus_order_tmp?
function setPromoterCartInfo($pid, $mv) {
    global $db;

    if(strstr($mv, "'"))  {
        $mv = str_replace("'", "\'", $mv);        
    }
    $sql = "SELECT `info` FROM `promoter_order_tmp` WHERE `promoter_id` = '$pid'";
    $t_value = $db->get_one($sql);
    if (!empty($t_value)) {
        $sql = "update `promoter_order_tmp` set `info` = '$mv' WHERE `promoter_id` = '$pid' limit 1";
    } else {
        $sql = "insert into `promoter_order_tmp` (`promoter_id`, `info`) values ('$pid', '$mv')";
    }
    if (!$db->query($sql)) {
        return false;
    }
}


// ?
function getCountryPic($coun) {
    switch ($coun) {
        case "Denmark" :
            return "<img src='images/danmai.gif' width='35' height='24'>";
            break;
        case "Hong Kong":
            return "<img src='images/hk.gif' width='35' height='24'>";
            break;
        case "China":
            return "<img src='images/china.gif' width='35' height='24'>";
            break;
        case "Sweden":
            return "<img src='images/sweden.gif' width='35' height='24'>";
            break;
        default:
            return $coun;
            break;
    }
}

function after ($this, $inthat) {
    if (!is_bool(strpos($inthat, $this))) {
        return substr($inthat, strpos($inthat,$this)+strlen($this));
    }
    return false;
}

function before ($this, $inthat) {
    return substr($inthat, 0, strpos($inthat, $this));
}

function between ($this, $that, $inthat) {
    return before($that, after($this, $inthat));
}

// add by allen 20070124
function getPrice($p, $v) {
    // $p ?? $v ? 0<=$v<100
    $v = floatval($v);
    if ($v<0) {
        return false;
    }
    return number_format($p*(100+$v)/100, 2, '.', '');
}

function getSpecialPrice($p, $v=0) {
    $v = floatval($v);
    if ($v<0) {
        return false;
    }
    return number_format($p*0.9*(100+$v)/100, 2, '.', '');
}

function getSpecialGroupPrice($p, $v=0) {
    $v = floatval($v);
    if ($v<0) {
        return false;
    }
    return number_format($p*0.85*(100+$v)/100, 2, '.', '');
}


function getPageStr($total, $page, $perpage, $link) {
    $pages = @ceil($total / $perpage);
    $pagelink = '';
    if ($pages == 1) {
        $pagelink = "";
        return "";
    } elseif ($page == 1 && $page<$pages) {
        $pagelink = '<a href="' . $link . 'page=' . ($page+1) . '">></a> <a href="' . $link . 'page=' . $pages . '">>></a>';
    } elseif ($page<$pages) {
        $pagelink = '<a href="' . $link . 'page=1"><<</a> <a href="' . $link . 'page=' . ($page-1) . '"><</a> <a href="' . $link . 'page=' . ($page+1) . '">></a> <a href="' . $link . 'page=' . $pages . '">>></a>';
    } elseif ($page == $pages) {
        $pagelink = '<a href="' . $link . 'page=1"><<</a> <a href="' . $link . 'page=' . ($page-1) . '"><</a>';
    }

    $final_num = $page*$perpage < $total ? $page*$perpage : $total;
    return '<table width=100% align=center border=0 cellspacing=0 cellpadding=0 height=24>
              <tr>
                <td align=left>&nbsp;' . (($page-1)*$perpage+1) . ' - ' . $final_num . ' of ' . $total . ' records</td>
                <td align=right>&nbsp;&nbsp;&nbsp;' . $pagelink . '&nbsp;</td>
              </tr>
            </table>';
}
function getRankAry($rankid)
{
	global $mysql;
	global $RANK_ARY;
	$rank_key="commission_rates_".strtolower($RANK_ARY[$rankid]);//??
	$sql="select mvalue from med_other where mkey='".$rank_key."'"; 
	$ary_rank=$mysql->fetch($sql);
	$rank_value=$ary_rank[0]["mvalue"];
	$ary_rank2=explode("||",$rank_value);//????3?????pay time
	return $ary_rank2;
}
function getPromoterConsume($pid)//??PROMOTER?????,??????
{
	global $mysql;
	$sql="select sum(cost)-sum(pay_amount) as consum from promoter_order where promoter_id=".$pid." and pay_flag=0";
	$ary_consum=$mysql->fetch($sql);
	$promoter_consum=$ary_consum[0][0];
	
	return $promoter_consum;
}
function getCmsPaidList($pid)//??PROMOTER??????
{
	global $mysql;
	$ptype=getPromoterType($pid);
	if($ptype=="1")
	{
		$sql="SELECT po.*,po.cost-po.pay_amount as commission,po.date as pay_date FROM  promoter_order po where promoter_id=$pid and po.pay_flag=0 ORDER BY `id` DESC";
	}
	else
	{
		$sql="select pc.*,cus.firstname,cus.lastname,cus.id  from `promoter_commission` pc, `cus_order` co,`cus_members` cus where  pc.order_id = co.id and pc.status=1  and co.pay_flag=0 and co.deliver_status=1 and co.user_id=cus.id and pc.promoter_id=$pid order by id desc";//????????????
	}
	$ary=$mysql->fetch($sql);
	return $ary;
}

function getCms($pid)//??PROMOTER????
{
	global $mysql;
	$cms_cms=0;
	$cms_notpaid=0;
	$cms_paid=0;
	$cms_osd=0;
	$cost=0;	
	$ptype=getPromoterType($pid);
	
	$sql="select pc.* from `promoter_commission` pc  inner join `cus_order` co on  pc.order_id = co.id and co.pay_flag=0 and co.deliver_status=1 and pc.promoter_id=$pid";//????????????
	$ary=$mysql->fetch($sql);
	
	for($i=0;$i<count($ary);$i++)
	{
		$cost+=$ary[$i]["cost"];
		$cms_cms+=$ary[$i]["commission"];
		if($ary[$i]["status"]=="0")
			$cms_notpaid+=$ary[$i]["commission"];
		else
			$cms_paid+=$ary[$i]["commission"];
	}
	$cms_osd=$cms_notpaid;
		
	if($ptype=="1")
	{
		$cms_consume=getPromoterConsume($pid);
		$cms_paid=$cms_consume+$cms_paid;
		$cms_osd=$cms_notpaid-$cms_consume;
	}
	if($cms_osd<0) $cms_osd=0;
	$cms["cms"]=number_format($cms_cms,2,"."," ");
	$cms["cms_notpaid"]=number_format($cms_notpaid,2,"."," ");
	$cms["cms_paid"]=number_format($cms_paid,2,"."," ");
	$cms["cms_osd"]=number_format($cms_osd,2,"."," ");
	$cms["cost"]=number_format($cost,2,"."," ");
	
	$cms["cms1"]=$cms_cms;
	$cms["cms_notpaid1"]=$cms_notpaid;
	$cms["cms_paid1"]=$cms_paid;
	$cms["cms_osd1"]=$cms_osd;
	$cms["cost1"]=$cost;

	return $cms;
}
function getVat()//???????VAT
{
	global $db;
	$sql="select pro_value from pro_values where pro_key='vat'";
	$ary=$db->get_one($sql);
	$vat=$ary["pro_value"];
	if($vat=="")
		$vat=10;
	return $vat;
}
function getPromoterType($pid)//??promoter???,?????????????
{
	global $db;
	$sql="select faq1 from promoter_info where id=$pid";
	$ary=$db->get_one($sql);
	return $ary["faq1"];
}
function filter($str)
{
	$str=htmlentities($str);
	//$str=str_replace("'","&#39")
	return $str;
}
function getOutPut($fileName,$width="",$height="",$path="../pictures/promotion/")
{
	$fileType = substr($fileName,strpos($fileName,".")+1);
	$imgAry = array("jpg","jpep","gif");
	$flashAry = array("swf","fla");
	$rtn = "";
	$width = $width == "" ? "" : " width=\"".$width."\"";
	$height = $height == "" ? "" : " height=\"".$height."\"";
	if(in_array($fileType,$imgAry))
	{
		$rtn = "<img src=\"".$path.$fileName."\"".$width.$height." border=0/>";
	}
	else if(in_array($fileType,$flashAry))
	{
		$rtn = "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\" ".$width.$height.">
  <param name=\"movie\" value=\"".$path.$fileName."\" />
  <param name=\"quality\" value=\"high\" />
  <embed src=\"".$path.$fileName."\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" ".$width.$height."></embed>
</object>";
	}
	else
	 	$rtn = "Unknow file type!";
	return $rtn;
}
?>